using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Volo.Abp;
using Volo.Abp.Data;
using Matrix.ServiceDiscovery;

namespace MatrixServiceDiscovery.DbMigrator
{
    class Program
    {
        static async Task<int> Main(string[] args)
        {
            Console.WriteLine("Matrix Service Discovery Database Migrator");
            Console.WriteLine("===========================================");

            try
            {
                // 创建主机构建器
                var builder = Host.CreateDefaultBuilder(args);

                builder.ConfigureServices((context, services) =>
                {
                    // 添加ABP服务
                    services.AddApplication<ServiceDiscoveryDbMigratorModule>();
                });

                // 构建主机
                var host = builder.Build();

                // 初始化并运行ABP应用
                await host.InitializeApplicationAsync();

                // 执行迁移
                var migratorService = host.Services.GetRequiredService<ServiceDiscoveryDbContextMigrationService>();
                var logger = host.Services.GetRequiredService<ILogger<Program>>();

                if (args.Length > 0)
                {
                    switch (args[0].ToLowerInvariant())
                    {
                        case "seed":
                            logger.LogInformation("执行种子数据");
                            await migratorService.SeedDataAsync();
                            break;

                        case "migrate-all":
                            logger.LogInformation("迁移所有租户数据库");
                            await migratorService.MigrateAllTenantsAsync();
                            logger.LogInformation("执行种子数据");
                            await migratorService.SeedDataAsync();
                            break;

                        case "migrate-host":
                            logger.LogInformation("迁移主机数据库");
                            await migratorService.MigrateHostAsync();
                            logger.LogInformation("执行种子数据");
                            await migratorService.SeedDataAsync();
                            break;

                        default:
                            if (Guid.TryParse(args[0], out var tenantId))
                            {
                                logger.LogInformation("迁移指定租户数据库: {TenantId}", tenantId);
                                await migratorService.MigrateTenantAsync(tenantId);
                            }
                            else
                            {
                                Console.WriteLine("未知参数: {Arg}", args[0]);
                                PrintUsage();
                                return 1;
                            }
                            break;
                    }
                }
                else
                {
                    // 默认操作：迁移所有租户
                    logger.LogInformation("默认操作：迁移所有租户数据库");
                    await migratorService.MigrateAllTenantsAsync();
                    logger.LogInformation("执行种子数据");
                    await migratorService.SeedDataAsync();
                }

                Console.WriteLine("数据库迁移完成！");
                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"迁移失败: {ex.Message}");
                Console.WriteLine($"详细错误: {ex}");
                return 1;
            }
        }

        private static void PrintUsage()
        {
            Console.WriteLine();
            Console.WriteLine("用法:");
            Console.WriteLine("  MatrixServiceDiscovery.DbMigrator [command]");
            Console.WriteLine();
            Console.WriteLine("命令:");
            Console.WriteLine("  (无参数)            迁移所有租户数据库并执行种子数据");
            Console.WriteLine("  migrate-all         迁移所有租户数据库并执行种子数据");
            Console.WriteLine("  migrate-host        迁移主机数据库并执行种子数据");
            Console.WriteLine("  migrate-tenant-id   迁移指定租户数据库（需要提供租户ID）");
            Console.WriteLine("  seed               只执行种子数据");
            Console.WriteLine();
            Console.WriteLine("示例:");
            Console.WriteLine("  MatrixServiceDiscovery.DbMigrator");
            Console.WriteLine("  MatrixServiceDiscovery.DbMigrator migrate-all");
            Console.WriteLine("  MatrixServiceDiscovery.DbMigrator migrate-host");
            Console.WriteLine("  MatrixServiceDiscovery.DbMigrator 12345678-1234-1234-1234-123456789012");
            Console.WriteLine("  MatrixServiceDiscovery.DbMigrator seed");
        }
    }
}